package com.waiting.java8.feature;

import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @Description
 * @Author bjweitingting
 * @Date 2018/10/9
 **/
public class OptionalTest {
    static User user;

    public static void main(String[] args) {

        Optional<User> optionalUser = Optional.ofNullable(user);
        Optional<User> optionalUserTwo = Optional.ofNullable(user);
        if (optionalUser.isPresent()) {
            System.out.println(optionalUser.get().age);
        } else {
            System.out.println("null");
        }
        //因为user为null，所以此时输出为：true
//        System.out.println("equal=" + optionalUser.equals(optionalUserTwo));
        user = new User();
        optionalUser = Optional.ofNullable(user);
        optionalUserTwo = Optional.ofNullable(user);
        //此时比较value，即user值，输出：true
        System.out.println("equal=" + optionalUser.equals(optionalUserTwo));


        optionalUser = optionalUser.filter(new Predicate<User>() {
            @Override
            public boolean test(User user) {
                return user == null ? false : true;
            }
        });
        System.out.println(optionalUser.get());
        //如果optional的value为null，则返回传参的
        User userTmp = optionalUser.orElse(new User("test"));
        System.out.println(userTmp.getName());

        optionalUser.orElseGet(new Supplier<User>() {
            @Override
            public User get() {
                return null;
            }
        });

        Object result = optionalUser.map(user -> {
            return null;
        }).orElse("name is null");
        System.out.println(result);
        Optional<String> stringOptional = Optional.ofNullable("System.out::println");
//        stringOptional.ifPresent( System.out::println);
        stringOptional.ifPresent(var -> {
            var = "修改var";
            System.out.println(var);
        });
        System.out.println(stringOptional.get());
        BinaryOperator<Integer> add = (x, y) -> x + y;
        System.out.println(add);
    }
}

class User {
    String name;
    Integer age;

    User() {

    }

    User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
